package com.concurrent.execute;

import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.concurrent.execute.threadPool.CallerRunsPolicy;
import com.concurrent.execute.threadPool.DaemonThreadFactory;
import com.concurrent.execute.threadPool.DynamicThreadPool;

/**
 * 异步执行
 * 
 * @author lkclkc88
 * 
 */
public class AsExecute {

	private static volatile int maxThread = 100;

	private static DynamicThreadPool pool;

	private static void init() {
		if (null == pool) {
			synchronized (AsExecute.class) {
				if (null == pool) {
					pool = new DynamicThreadPool(1, maxThread, 60L, TimeUnit.SECONDS,
							new LinkedBlockingQueue<Runnable>(10000), new DaemonThreadFactory(),
							new CallerRunsPolicy());
				}
			}
		}
	}

	/**
	 * 启动任务之前调用才有效果
	 * 
	 * @param maxThread
	 */
	public static void changeMaxThread(int maxThread) {
		if (maxThread >= 1 && null == pool) {
			AsExecute.maxThread = maxThread;
		}
	}

	/**
	 * 异步执行任务
	 * 
	 * @param task
	 * @return
	 */
	public static <T> AsExecuteResult<T> execute(Callable<T> task) {
		init();

		return (AsExecuteResult<T>) pool.submit(task);
	}
}
